/*
 * Copyright (c) 2011 Imre Fazekas.
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 * Neither the name of the Brillien nor the names of its
 * terms and concepts may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

package com.vii.streamline.webserver;

import com.vii.streamline.structures.collections.InnerList;
import org.glassfish.grizzly.http.server.HttpHandler;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.grizzly.http.server.ServerConfiguration;
import org.glassfish.grizzly.servlet.ServletRegistration;
import org.glassfish.grizzly.servlet.WebappContext;
import org.glassfish.grizzly.websockets.WebSocketAddOn;
import org.glassfish.grizzly.websockets.WebSocketApplication;
import org.glassfish.grizzly.websockets.WebSocketEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.Servlet;
import java.io.IOException;
import java.util.Map;


public class WebServer {
    public static Logger                    logger;

    public static String                    HOST                        = "localhost";
    public static int                       PORT                        = 7777;
    public static String                    SERVER_NAME                 = "BrillienWebServer";
    public static String                    DOC_ROOT                    = "res/www";

    public static HttpServer                server;
    public static ServerConfiguration       config;

    static{
        logger = LoggerFactory.getLogger( WebServer.class );
    }

    private static void log( String message ){
        if( logger != null )
            logger.info(message);
    }

    public static void initServer() throws IOException {
        if( server != null )
            stopServer();

        log( "Starting web server..." + " with root folder:" + DOC_ROOT );

        server = HttpServer.createSimpleServer(DOC_ROOT, PORT);

        config = server.getServerConfiguration();
        config.setName(HOST);
        config.setHttpServerName(SERVER_NAME);
    }

    public static void startServer() throws IOException {
        if( server != null )
            server.start( );
    }

    public static void addHttpService(final String context, final String servletName, Servlet servlet) {
        addHttpService( context, servletName, servlet, null );
    }

    public static void addHttpService(final String context, final String servletName, Servlet servlet, Map<String, String> map, final String... mappings) {
        log("Servlet added with context:" + context + "  servletName:" + servletName + "  mappings:" + new InnerList<String>(mappings) + " with instance:" + servlet);

        WebappContext ctx = new WebappContext(servletName, context);
        final ServletRegistration reg = ctx.addServlet( servletName, servlet );

        if( map != null )
            for( String key : map.keySet() )
                reg.setInitParameter( key, map.get( key ));

        if( mappings.length > 0 )
            reg.addMapping( mappings );
        else
            reg.addMapping( servletName );

        ctx.deploy(server);
    }

    public static void addHttpHandler(String context, HttpHandler httpHandler) {
        config.addHttpHandler(httpHandler, context);
    }

    public static void activateWebsockets(){
        log("Websocket activated.");

        server.getListener("grizzly").registerAddOn(new WebSocketAddOn());
    }

    public static void addWebSocketApplication( String name, WebSocketApplication application ){
        log( application.getClass().getName() + " webSocket application added with name:" + name );

        WebSocketEngine.getEngine().register(name, application);
    }

    public static void stopServer(){
        try{
            log( "Stopping web server..." );
            server.stop();
            server = null;
        } catch(Exception e){}
    }

}
